package com.webridge.plm.util;

import java.lang.reflect.Method;

import org.apache.log4j.Logger;

import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.fc.WTReference;
import wt.inf.container.OrgContainer;
import wt.inf.container.WTContainer;
import wt.inf.library.WTLibrary;
import wt.log4j.LogR;
import wt.method.RemoteMethodServer;
import wt.org.DirectoryContextProvider;
import wt.org.OrganizationServicesHelper;
import wt.org.WTGroup;
import wt.org.WTPrincipal;
import wt.org.WTPrincipalReference;
import wt.org.WTUser;
import wt.pdmlink.PDMLinkProduct;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionContext;
import wt.session.SessionHelper;
import wt.util.WTException;
import wt.vc.Iterated;
import wt.vc._IterationInfo;

public class WCUtil {
	
	private final static Logger LOGGER = LogR.getLogger(WCUtil.class.getName());
	
	 public static WTContainer getWtContainerByName(String name) throws WTException
	    {
	        WTContainer obj = null;
	        if (!RemoteMethodServer.ServerFlag)
	        {
	            try
	            {
	                Class aclass[] = 
	                { String.class };
	                Object aobj[] =
	                { name };
	                obj = (WTContainer) RemoteMethodServer.getDefault().invoke("getWtContainerByName",
	                        WCUtil.class.getName(), null, aclass, aobj);
	            } catch (Exception e)
	            {
	                LOGGER.error(e.getMessage(), e);
	                throw new WTException(e);
	            }
	        }
	        else
	        {
	            QuerySpec qs = new QuerySpec(WTContainer.class);
	            QueryResult qr = null;
	            SearchCondition sc = new SearchCondition(WTContainer.class, WTContainer.NAME, "=", name);
	            qs.appendWhere(sc);
	            qr = PersistenceServerHelper.manager.query(qs);

	            while (qr.hasMoreElements())
	            {
	                obj = (WTContainer) qr.nextElement();
	            }
	        }
	        return obj;
	    }
	 
	  public static WTContainer getContainer(String name) throws WTException {
	        QuerySpec qs = new QuerySpec(PDMLinkProduct.class);
	        PDMLinkProduct product = null;
	        SearchCondition sc = new SearchCondition(PDMLinkProduct.class, PDMLinkProduct.NAME, SearchCondition.EQUAL,
	                name);
	        qs.appendWhere(sc);
	        QueryResult qr = wt.fc.PersistenceHelper.manager.find(qs);
	        while (qr.hasMoreElements()) {
	            product = (PDMLinkProduct) qr.nextElement();
	        }
	        if (product != null) {
	            return product;
	        }
	        QuerySpec qs1 = new QuerySpec(WTLibrary.class);
	        WTLibrary library = null;
	        SearchCondition sc1 = new SearchCondition(WTLibrary.class, WTLibrary.NAME, SearchCondition.EQUAL, name);
	        qs1.appendWhere(sc1);
	        QueryResult qr1 = wt.fc.PersistenceHelper.manager.find(qs1);
	        while (qr1.hasMoreElements()) {
	            library = (WTLibrary) qr1.nextElement();
	        }
	        return library;
	    }
	 
	 
	 public static Persistable getPersistableByOid(String oid) throws WTException
	    {
	        Persistable p = null;
	        if (!RemoteMethodServer.ServerFlag)
	        {
	            try
	            {
	                Class aclass[] =
	                { String.class };
	                Object aobj[] =
	                { oid };
	                p = (Persistable) RemoteMethodServer.getDefault().invoke("getPersistableByOid", WCUtil.class.getName(),
	                        null, aclass, aobj);
	            } catch (Exception e)
	            {
	                // e.printStackTrace();
	                LOGGER.error(e.getMessage(), e);
	                throw new WTException(e);
	            }

	        }
	        else
	        {
	            WTUser previous = null;
	            WTPrincipal wtadministrator = null;
	            try
	            {
	                // session exchange
	                previous = (WTUser) SessionHelper.manager.getPrincipal();
	                wtadministrator = SessionHelper.manager.getAdministrator();
	                SessionContext.setEffectivePrincipal(wtadministrator);
	                SessionHelper.manager.setAdministrator();

	                ReferenceFactory rf = new ReferenceFactory();
	                WTReference wtr = rf.getReference(oid);
	                if (wtr != null)
	                {
	                    p = wtr.getObject();
	                }
	            } catch (WTException e)
	            {
	                LOGGER.error("getPersistableByOid2():", e);
	                throw new WTException(e);
	            } finally
	            {
	                if (previous != null) {
	                    SessionHelper.manager.setPrincipal(previous.getName());
	                    SessionContext.setEffectivePrincipal(previous);
	                }
	            }
	        }
	        return p;
	    }
	 
	 
	 public static void setCreatorOrModifier(Iterated obj, WTPrincipalReference uref, String methodName) {
	        try {
	            Class[] pp = new Class[] { WTPrincipalReference.class };
	            Method setCreatorOrModifier = _IterationInfo.class.getDeclaredMethod(methodName, pp);// setCreator;setModifier
	            setCreatorOrModifier.setAccessible(true);
	            obj = (Iterated) PersistenceHelper.manager.refresh((Persistable) obj, false, true);
	            setCreatorOrModifier.invoke(obj.getIterationInfo(), new Object[] { uref });
	            PersistenceServerHelper.manager.update(obj);

	        } catch (Exception e) {
	            
	            LOGGER.error(LOGGER, e);
	        }
	    }
	 
	 
	 public static WTGroup getGroupByName(String name) throws WTException{
	        WTGroup group = null;
	        DirectoryContextProvider context;
	        try {
	            context = OrganizationServicesHelper.manager.newDirectoryContextProvider(
	                    (String[]) null, (String[]) null);
	            group = OrganizationServicesHelper.manager.getGroup(name, context);
	        } catch (WTException e) {
	        	LOGGER.error("Get group for ["+name+"] error.", e);
	            throw new WTException(e, "Get group for ["+name+"] error.");
	        }
	        return group;
	    }
	 
	 
	 public static WTGroup getGroupByOrganization(String groupName) throws WTException{
		 WTGroup group = null ;
		 try{
				 QuerySpec qs = new QuerySpec();
				 int orgIndex = qs.appendClassList( OrgContainer.class, true );
				 SearchCondition sc = new SearchCondition( OrgContainer.class, "containerInfo.name", SearchCondition.EQUAL, "x1929" );
				 qs.appendWhere( sc );
				 QueryResult qr = PersistenceHelper.manager.find( qs );
				 if( qr.hasMoreElements() ) {
	                 Persistable [] p = ( Persistable [] ) qr.nextElement();
	                 OrgContainer org = ( OrgContainer ) p[0];
	                 group = OrganizationServicesHelper.manager.getGroup(groupName, org.getContextProvider() );
	                 System.out.println("THE GROUP: " + group);                                                     
				 }
				 return group ;
			 } catch(Exception e){
				 e.printStackTrace();
			 }
		 return group ;
	 } 
}
